//
//  ZNT_MapViewController.m
//  B
//
//  Created by Znt on 15/11/12.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "ZNT_MapViewController.h"

#import "MKAnnotation.h"
#import "Model4.h"
#import "Day.h"
#import "TravelViewController.h"


@interface ZNT_MapViewController ()<MKMapViewDelegate>

@property (nonatomic)CLLocationCoordinate2D begin_coordinate;
@property (nonatomic)CLLocationCoordinate2D coordinate;
@property (nonatomic, retain)UIButton *btn;
@property (nonatomic, retain)UIButton *pushBtn;
@property (nonatomic, assign)BOOL flag;
@property (nonatomic, retain)UIView *photoView;
@property (nonatomic, retain)UIImageView *imageView;
@property (nonatomic, retain)UIImageView *bgView;
@property (nonatomic, retain)MKAnnotation *tmpAnno;
@end

@implementation ZNT_MapViewController



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = YES;
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"0000000000000%@",self.allDataArray);
    self.annoArray = [NSMutableArray array];
    [self setMap];
    [self addNextAndPreBtn];
    [self showPhoto:self.current];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *image = [UIImage imageNamed:@"add_new_poi_back_btn"];
    UIImage *img = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)addNextAndPreBtn{
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_next_button@2xpng"] forState:UIControlStateNormal];
    nextBtn.frame = CGRectMake(375 *XWIDTH *0.6, 667 *XHIGHT*0.75, 375 *XWIDTH *0.2, 667 *XHIGHT*0.1);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = nextBtn.height/2;
    nextBtn.backgroundColor = [UIColor blackColor];
    nextBtn.alpha = 0.5;
    [nextBtn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:nextBtn];
    
    UIButton *preBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [preBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_previous_button"] forState:UIControlStateNormal];
    preBtn.frame = CGRectMake(375 *XWIDTH  *0.2, 667 *XHIGHT*0.75, 375 *XWIDTH  *0.2, 667 *XHIGHT*0.1);
    preBtn.layer.masksToBounds = YES;
    preBtn.layer.cornerRadius = preBtn.height/2;
    preBtn.backgroundColor = [UIColor blackColor];
    preBtn.alpha = 0.5;
    [preBtn addTarget:self action:@selector(pre) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:preBtn];
    
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playBtn setImage:[UIImage imageNamed:@"trip_map_fullscreen_play_button"] forState:UIControlStateNormal];
    playBtn.frame = CGRectMake(375 *XWIDTH  *0.4, 667 *XHIGHT*0.75, 375 *XWIDTH  *0.2, 667 *XHIGHT*0.1);
    playBtn.layer.masksToBounds = YES;
    playBtn.layer.cornerRadius = playBtn.height/2;
    playBtn.backgroundColor = [UIColor blackColor];
    playBtn.alpha = 0.5;
    [playBtn addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.map addSubview:playBtn];
}

- (void)play:(UIButton *)btn{
    if (self.isPlay) {
        [self.timer invalidate];
        self.timer = nil;
        [btn setImage:[UIImage imageNamed:@"trip_map_fullscreen_play_button"]forState:UIControlStateNormal];
    }
    else{
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
        [btn setImage:[UIImage imageNamed:@"trip_map_fullscreen_pause_button"]forState:UIControlStateNormal];
    }
    self.isPlay = !self.isPlay;
}

- (void)next{
    if (self.current<self.annoArray.count-1) {
        self.current++;
        [self showPhoto:self.current];
    }
}

- (void)pre{
    if (self.current>0) {
        self.current--;
        [self showPhoto:self.current];
    }
}

- (void)showPhoto:(NSInteger)current{
    NSLog(@"------%ld",self.annoArray.count);
    Model4 *day = [self.annoArray objectAtIndex:current];
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
    
    [self.map setCenterCoordinate:coordinate];
    
    [self addPhotoAnnotation:day Current:current];
}

- (UIView *)addPhotoView:(NSString *)imageUrl{
    
    if (self.photoView != nil) {
        
        [self.photoView removeFromSuperview];
        
    }
    self.photoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH*0.5, WIDTH*0.35)];
    
    
    self.bgView = [[UIImageView alloc]initWithFrame:self.photoView.bounds];
    self.bgView.image = [UIImage imageNamed:@"trip_map_callout_bg"];
    [self.photoView addSubview:self.bgView];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.bgView.width *0.92, self.bgView.height * 0.9)];
    self.imageView.center = CGPointMake(self.bgView.width/2, self.bgView.height/2 - self.bgView.height*0.03);
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"place_holder_cell"]];
    [self.bgView addSubview:self.imageView];
    
    self.pushBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.pushBtn.frame = self.photoView.bounds;
    [self.pushBtn addTarget:self action:@selector(pushDetail) forControlEvents:UIControlEventTouchUpInside];
    [self.photoView addSubview:self.pushBtn];
    
    return self.photoView;
}

- (void)pushDetail{
    NSLog(@"push");
    //    TravelDetailViewController *detail = [[TravelDetailViewController alloc]init];
    //    detail.current = self.current;
    //    detail.UrlStr = self.urlStr;
    //    [self.navigationController pushViewController:detail animated:YES];
    //    [detail release];
}


-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    
    MKAnnotation *anno = (MKAnnotation *)view.annotation;
    
    self.current = anno.current;
    
    [self addPhotoAnnotation:[self.annoArray objectAtIndex:self.current]  Current:self.current];
    NSLog(@"%@",NSStringFromCGRect(view.frame));
    NSLog(@"%@",NSStringFromCGRect(self.photoView.frame));
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"%@",touches);
}
//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//    UIView *v = [self.view hitTest:point withEvent:event];
//    if (v == nil) {
//        CGPoint tp = [self.pushBtn convertPoint:point fromView:self.view];
//        if (CGRectContainsPoint(self.pushBtn.bounds, tp)) {
//            v = self.pushBtn;
//        }
//    }
//
//    return v;
//}


- (void)addPhotoAnnotation:(Model4 *)day Current:(NSInteger)current{
    
    MKAnnotation *anno = [[MKAnnotation alloc]init];
    
    anno.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
    anno.category = [day.category stringValue];
    anno.current = current;
    
    [self.map addAnnotation:anno];
    
    
}

- (void)addAnnotation:(Model4 *)day Current:(NSInteger)current{
    
    if (self.coordinate.latitude != [day.latitude floatValue]&&self.coordinate.longitude != [day.longitude floatValue]) {
        MKAnnotation *anno = [[MKAnnotation alloc]init];
        anno.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
        anno.category = [day.category stringValue];
        anno.current = current;
        [self.map addAnnotation:anno];
        
    }
    
    if (self.coordinate.longitude != 0 && self.coordinate
        .latitude != 0) {
        CLLocationCoordinate2D pathCoords[2] =
        {
            self.coordinate,
            CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue])
        };
        MKPolyline *pathOverlay = [MKPolyline polylineWithCoordinates:pathCoords count:2];
        
        [self.map addOverlay:pathOverlay];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    static NSString *ID = @"Anno";
    MKAnnotationView *annoView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView == nil) {
        annoView = [[MKAnnotationView alloc]initWithAnnotation:nil reuseIdentifier:nil];
    }
    
    MKAnnotation *myAnnotation = (MKAnnotation *)annotation;
    
    Model4 *day = [self.annoArray objectAtIndex:myAnnotation.current];
    
    UIView *tmpView = [self addPhotoView:day.photo_1600];
    tmpView.center = CGPointMake(annoView.width/2 + WIDTH * 0.02 , 0);
    tmpView.y = annoView.y - tmpView.height - annoView.height;
    
    [annoView addSubview:tmpView];
    
    if (myAnnotation.category.length == 0) {
        annoView.image = [UIImage imageNamed:@"map_text"];
    }
    else{
        NSString *imageName = [NSString stringWithFormat:@"annotation_%@",myAnnotation.category];
        annoView.image = [UIImage imageNamed:imageName];
    }
    
    return annoView;
}

- (void)setMap{
    
    self.map = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, 375 *XWIDTH, 667 *XHIGHT - 64)];
    self.map.mapType = MKMapTypeStandard;
    self.map.delegate = self;
    [self.view addSubview:self.map];
    
    NSInteger current = 0;
    
    for (int i = 0; i<self.allDataArray.count; i++) {
        
        Day *days = [self.allDataArray objectAtIndex:i];
        for (int j = 0; j < days.waypoints.count;j++) {
            
            Model4 *day = [days.waypoints objectAtIndex:j];
            NSLog(@"88888888888%@",day.latitude);
            if (day.latitude != nil) {
                
                if (current == 0) {
                    self.begin_coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
                }
                [self addAnnotation:day Current:current];
                [self.annoArray addObject:day];
                
                self.coordinate = CLLocationCoordinate2DMake([day.latitude floatValue], [day.longitude floatValue]);
                current++;
            }
            NSLog(@"9090909090%@",day );
        }
    }
    MKCoordinateSpan span = MKCoordinateSpanMake(0.45, 0.3);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.begin_coordinate, span);
    [self.map setRegion:region animated:YES];
    
}


-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *renderer=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
       // renderer.strokeColor=MBCOLOR;
        renderer.lineWidth=1.0;
        return renderer;
    }
    return nil;
}


- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    [self.map removeFromSuperview];
    [self.view addSubview:mapView];
}

- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
}

@end


